package cn.edu.jxau.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 邻接矩阵实现无向图
 * 
 * 所需的空间与顶点的平方数成正比，所以当顶点非常多时，空间的消耗是无法接受的
 * 获取与顶点v相邻的所以顶点需要遍历一个大小为v的数组
 * 综上，时间空间都不是很理想
 * 
 * @author 付大石
 */
public class Graph {

    public static void main(String[] args) {
        Graph g = new Graph(13);
        g.addEdge(0, 5);
        g.addEdge(4, 3);
        g.addEdge(0, 1);
        g.addEdge(9, 12);
        g.addEdge(6, 4);
        g.addEdge(5, 4);
        g.addEdge(0, 2);
        g.addEdge(11, 12);
        g.addEdge(9, 10);
        g.addEdge(0, 6);
        g.addEdge(7, 8);
        g.addEdge(9, 11);
        g.addEdge(5, 3);
        for (int i : g.adj(0)) {
            System.out.print(i + " ");
        }
        System.out.println();
        System.out.println(g.v());
        System.out.println(g.e());
        g.printMatrix();
    }

    /**
     * vertex 顶点数目
     */
    private final int v;

    /**
     * edge 边的数目
     */
    private int e;

    /**
     * 邻接矩阵
     */
    private boolean[][] matrix;

    public Graph(int v) {

        this.v = v;
        matrix = new boolean[v][v];
    }

    public int v() {
        return v;
    }

    public int e() {
        return e;
    }

    public void addEdge(int v, int w) {

        if (v >= this.v) {
            throw new IllegalArgumentException("顶点不存在，v=" + v);
        }
        if (w >= this.v) {
            throw new IllegalArgumentException("顶点不存在，w=" + w);
        }
        matrix[v][w] = true;
        matrix[w][v] = true;
        e++;
    }

    /**
     * 获取与顶点{@param v}相邻的的顶点
     * @param v
     * @return
     */
    public Iterable<Integer> adj(int v) {

        System.out.println(Arrays.toString(matrix[v]));
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < matrix[v].length; i++) {
            if (matrix[v][i]) {
                list.add(i);
            }
        }
        return list;
    }

    /**
     * 打印邻接矩阵
     */
    public void printMatrix() {
        for (int i = 0; i < v; i++) {
            for (int j = 0; j < v; j++) {
                if(matrix[i][j]) {
                    System.out.print("1 ");
                } else {
                    System.out.print("0 ");
                }
            }
            System.out.println();
        }
    }
}
